import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { customLogger } from './services/logger.service';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: ['error'],
  });
  app.enableCors();

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );

  //通过配置服务，获取端口
  const configService = app.get(ConfigService);
  const SERVICE_GLOBAL_PREFIX = configService.get('SERVICE_GLOBAL_PREFIX');
  const PORT = configService.get('SERVICE_PORT');
  app.setGlobalPrefix(SERVICE_GLOBAL_PREFIX);

  //动态配置日志
  const enableLog = configService.get('LOG_ENABLE');
  if (enableLog == 'true') {
    app.useLogger(customLogger(configService));
  }

  const options = new DocumentBuilder()
    .setTitle('YMBlog')
    .setDescription('YMBlog接口文档')
    .setVersion('1.0')
    .addTag('YMBlog')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('ym/api-docs', app, document); // 设置访问路径

  //捕获未catch的promise，防止挂掉
  process.on('uncaughtException', (reason) => {
    const loggerFormat = `
    timestamp:${new Date().toJSON()} \r\n
    reason:${reason} 
    \r\n
  `;
    Logger.error(loggerFormat);
  });
  process.on('unhandledRejection', (reason) => {
    const loggerFormat = `
    timestamp:${new Date().toJSON()} \r\n
    reason:${reason} 
    \r\n
  `;
    Logger.error(loggerFormat);
  });

  await app.listen(PORT);
}
bootstrap();
